package tools

import (
	"../config"
	"fmt"
	"github.com/Unknwon/com"
	"github.com/gpmgo/gopm/modules/log"
	"io/ioutil"
	"os"
	"strings"
)

/**
缓存文件
*/
var fileCache map[string][]byte

/**
缓存页面
*/
var pageCache map[string][]byte

func init() {
	fileCache = make(map[string][]byte)
	pageCache = make(map[string][]byte)
	readFileAs("examples/index.html", "index")
}

func ReadFile(filePath string) []byte {
	return readFileAs(filePath, filePath)
}

func readFileAs(filePath string, name string) []byte {
	if fileCache[name] != nil {
		fmt.Printf("数据对象的地址：%p\n", fileCache[name])
		return fileCache[name]
	}
	pageByte, _ := ioutil.ReadFile(filePath)
	if config.Conf.UseFileCache {
		fileCache[name] = pageByte
	}
	println("文件不存在,从磁盘读取")
	return pageByte
}

func CreateHtml(mdPath string) []byte {

	if pageCache[mdPath] != nil {
		log.Info("使用缓存，直接从缓存中取数据")
		return pageCache[mdPath]
	}
	log.Info("没有缓存，读取文件")
	md := mdPath
	mdByte := ReadFile(md)
	mdStr := string(mdByte)

	indexPage := ReadFile(config.Conf.IndexPage)
	pageStr := string(indexPage)

	pageStr = strings.ReplaceAll(pageStr, "${content}", mdStr)
	pageStr = strings.ReplaceAll(pageStr, "${checkedFile}", mdPath)

	pageByte := []byte(pageStr)

	if config.Conf.UseFileCache {
		pageCache[mdPath] = pageByte
		log.Info("使用缓存，记录缓存记录")
	}

	return pageByte
}

func ReadDirAll(path string) []FileContent {
	return ReadDirAllDo(path, 0)
}

func ReadDirAllDo(path string, index int) []FileContent {
	fileInfos, _ := ioutil.ReadDir(path)

	pathArray := []FileContent{}
	fileArray := []FileContent{}
	for _, info := range fileInfos {
		if strings.HasPrefix(info.Name(), ".") {
			continue
		}
		index++
		//判断是否是目录
		if info.IsDir() {
			pathArray = append(pathArray, FileContent{
				Id:      index,
				Name:    info.Name(),
				Path:    path + info.Name(),
				Href:    "/file/" + path + info.Name(),
				IsDir:   true,
				Checked: false,
				Next:    ReadDirAllDo(PathFormat(path+"/"+info.Name()), index*100),
				Spread:  false,
			})
		} else {
			fileArray = append(fileArray, FileContent{
				Id:      index,
				Name:    info.Name(),
				Path:    path + info.Name(),
				Href:    "/file/" + path + info.Name(),
				IsDir:   false,
				Checked: false,
				Next:    nil,
				Spread:  false,
			})
		}
	}
	pathArray = append(pathArray, fileArray...)
	return pathArray
}

func ReadDir(path string) []FileContent {
	file, err := os.OpenFile(path, os.O_RDONLY, os.ModeDir)

	defer func() {
		if file != nil {
			file.Close()
		}
	}()

	if err != nil {
		return nil
	}
	pathArray := []FileContent{}
	fileArray := []FileContent{}

	fileInfo, _ := file.Readdir(-1)

	for _, info := range fileInfo {
		//判断是否是目录
		if info.IsDir() {
			pathArray = append(pathArray, FileContent{
				Name:  info.Name(),
				Path:  path + info.Name(),
				IsDir: true,
			})
		} else {
			fileArray = append(fileArray, FileContent{
				Name:  info.Name(),
				Path:  path + info.Name(),
				IsDir: false,
			})
		}
	}
	pathArray = append(pathArray, fileArray...)
	return pathArray
}

func PathFormat(path string) string {
	decode := FilePathFormat(path)
	if !strings.HasSuffix(decode, "/") {
		decode = decode + "/"
	}
	return decode
}

func FilePathFormat(path string) string {
	decode, _ := com.UrlDecode(path)
	decode, _ = com.UrlDecode(decode)
	for strings.Contains(decode, "//") {
		decode = strings.ReplaceAll(decode, "//", "/")
	}
	return decode
}

type FileContent struct {
	Id      int           `json:"id"`
	Name    string        `json:"title"`
	Path    string        `json:"path"`
	Href    string        `json:"href"`
	IsDir   bool          `json:"isDir"`
	Checked bool          `json:"checked"`
	Spread  bool          `json:"spread"`
	Next    []FileContent `json:"children"`
}
